package com.dailyblue.javaee.controller;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;

    @WebServlet("/user_login_code")
    public class UserCodeController extends HttpServlet {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 首先需要一张图片
            int width = 150;
            int height = 30;
            // 图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 需要一支画笔
            Graphics graphics = image.getGraphics();
            // 填充颜色
            graphics.setColor(Color.GRAY);
            graphics.fillRect(0, 0, width, height);

            // 输出文字
            // 设置文字颜色
            int red = (int) (Math.random() * 256);
            int green = (int) (Math.random() * 256);
            int blue = (int) (Math.random() * 256);
            Color color = new Color(red, green, blue);
            graphics.setColor(color);
            // 设置文字大小
            Font font = new Font("宋体",Font.BOLD,24);
            graphics.setFont(font);
            graphics.drawString(getCodeString(request.getSession()), 20, 21);
            // 输出图片 图片，图片的类型，输出
            ImageIO.write(image, "jpg", response.getOutputStream());
        }

        private String getCodeString(HttpSession session) {
            StringBuilder str = new StringBuilder("");
            for (int i = 0; i < 4; i++) {
                int number = (int) (Math.random() * 26 + 65);
                char ch = (char) number;
                str.append(ch);
            }
            session.setAttribute("CODE",str.toString());
            return str.toString();
        }
    }